package com.logos.ruralrevitalization.service.impl;

import com.alibaba.fastjson.JSON;
import com.logos.ruralrevitalization.constant.RedisConstant;
import com.logos.ruralrevitalization.controller.TouristAttractionsController;
import com.logos.ruralrevitalization.converter.AgriculturalProductConverter;
import com.logos.ruralrevitalization.converter.TouristAttractionConverter;
import com.logos.ruralrevitalization.entity.AgriculturalProduct;
import com.logos.ruralrevitalization.entity.AuthUser;
import com.logos.ruralrevitalization.entity.TouristAttractions;
import com.logos.ruralrevitalization.enums.IsDeleteFlagEnum;
import com.logos.ruralrevitalization.mapper.AuthUserMapper;
import com.logos.ruralrevitalization.mapper.TouristAttractionsMapper;
import com.logos.ruralrevitalization.redis.RedisUtil;
import com.logos.ruralrevitalization.req.TouristAttractionsReq;
import com.logos.ruralrevitalization.resp.AgriculturalProductResp;
import com.logos.ruralrevitalization.resp.AttractionReviewsResp;
import com.logos.ruralrevitalization.resp.TouristAttractionsResp;
import com.logos.ruralrevitalization.service.TouristAttractionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 旅游景点表(TouristAttractions)表服务实现类
 */
@Service("touristAttractionsService")
@Slf4j
public class TouristAttractionsServiceImpl implements TouristAttractionsService {
    @Resource
    private TouristAttractionsMapper touristAttractionsMapper;

    @Resource
    private AttractionReviewsServiceImpl attractionReviewsService;

    @Resource
    private AuthUserMapper authUserMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     */
    @Override
    public TouristAttractions queryById(Integer id) {
        return this.touristAttractionsMapper.queryById(id);
    }

    /**
     * 新增数据
     */
    @Override
    public TouristAttractions insert(TouristAttractions touristAttractions) {
        this.touristAttractionsMapper.insert(touristAttractions);
        return touristAttractions;
    }

    /**
     * 修改数据
     */
    @Override
    public TouristAttractions update(TouristAttractions touristAttractions) {
        this.touristAttractionsMapper.update(touristAttractions);
        return this.queryById(touristAttractions.getId());
    }

    /**
     * 通过主键删除数据
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.touristAttractionsMapper.deleteById(id) > 0;
    }

    /**
     * 查询景点（可根据类型）
     */
    @Override
    public List<TouristAttractionsResp> queryByType(TouristAttractionsReq touristAttractionsReq) {
        TouristAttractions touristAttractions = TouristAttractionConverter.INSTANCE.convertReqToEntity(touristAttractionsReq);
        // 拿到当前页码和每页显示条数
        int pageNo = touristAttractionsReq.getPageNo();
        int pageSize = touristAttractionsReq.getPageSize();
        log.info("touristAttractionsReq:{}", touristAttractionsReq);
//        // 判断当前用户是否选择 评分优先或者价格优先
        Map<String, String> sortMap = new HashMap<>();
        if (touristAttractionsReq.getIsPrice() != null && touristAttractionsReq.getIsPrice()) {
            sortMap.put("price", "asc");
        } else if (touristAttractionsReq.getIsRating() != null && touristAttractionsReq.getIsRating()) {
            sortMap.put("rating", "desc");
        }
        // 查询未删除的
        touristAttractions.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<TouristAttractions> touristAttractionList = touristAttractionsMapper.queryAllByLimit(touristAttractions, pageNo, pageSize, sortMap);
        if (touristAttractionList == null || touristAttractionList.isEmpty()) {
            return null;
        }
        List<TouristAttractionsResp> touristAttractionsRespLinkedList = new LinkedList<>();
        for (TouristAttractions touristAttraction : touristAttractionList) {
            TouristAttractionsResp touristAttractionsResp = TouristAttractionConverter.INSTANCE.convertEntityToResp(touristAttraction);
//            // 计算评分
//            BigDecimal rating = new BigDecimal("0.0");
//            List<AttractionReviewsResp> attractionReviewsRespList = attractionReviewsService.queryByAttractionId(touristAttraction.getId());
//            for (AttractionReviewsResp attractionReviewsResp : attractionReviewsRespList) {
//                rating = rating.add(new BigDecimal(attractionReviewsResp.getRating()));
//            }
//            // 如果评论不为空，则计算平均分
//            if (attractionReviewsRespList.size() != 0) {
//                // 四舍五入,保留小数点后两位
//                rating = rating.divide(new BigDecimal(attractionReviewsRespList.size()), 2, RoundingMode.HALF_UP);
//            }
//            touristAttractionsResp.setRating(rating.doubleValue());
            touristAttractionsRespLinkedList.add(touristAttractionsResp);
        }
        // 评分优先
        if (touristAttractionsReq.getIsRating() != null && touristAttractionsReq.getIsRating()) {
            touristAttractionsRespLinkedList.sort((o1, o2) -> Double.compare(o2.getRating(), o1.getRating()));
        }
        // 价格优先
        if (touristAttractionsReq.getIsPrice() != null && touristAttractionsReq.getIsPrice()) {
            touristAttractionsRespLinkedList.sort((o1, o2) -> Double.compare(o1.getPrice(), o2.getPrice()));
        }
        return touristAttractionsRespLinkedList;
    }

    @Override
    public List<TouristAttractionsResp> queryHotRank() {
        // 判断缓存中是否存在数据
        if (redisUtil.exist(RedisConstant.TOURIST_ATTRACTIONS_HOT_RANK)) {
            String jsonStr = redisUtil.get(RedisConstant.TOURIST_ATTRACTIONS_HOT_RANK);
            List<TouristAttractionsResp> result = JSON.parseArray(jsonStr, TouristAttractionsResp.class);
            return result;
        }
        List<TouristAttractionsResp> result = touristAttractionsMapper.queryHotRank();
        if (result != null && result.size() > 0) {
            // 不为空，存入缓存
            redisUtil.setNx(RedisConstant.TOURIST_ATTRACTIONS_HOT_RANK, JSON.toJSONString(result), 2L, TimeUnit.MINUTES);
        }
        return result;
    }

    @Override
    public TouristAttractionsResp queryDetail(Integer id) {
        // 查询该景点的信息
        TouristAttractions touristAttractions = touristAttractionsMapper.queryById(id);
        TouristAttractionsResp touristAttractionsResp = TouristAttractionConverter.INSTANCE.convertEntityToResp(touristAttractions);
        // 查询和该景点相关的所有评论
        List<AttractionReviewsResp> attractionReviewsRespList = attractionReviewsService.queryByAttractionId(id);
        // 查询评论的用户信息
        for (AttractionReviewsResp attractionReviewsResp : attractionReviewsRespList) {
            AuthUser authUser = authUserMapper.queryById(Long.valueOf(attractionReviewsResp.getUserId()));
            attractionReviewsResp.setUserName(authUser.getUserName());
            attractionReviewsResp.setUserAvatar(authUser.getAvatar());
        }
        // 组装返回结果
        touristAttractionsResp.setAttractionReviewsRespList(attractionReviewsRespList);
        return touristAttractionsResp;
    }

    @Override
    public List<TouristAttractionsResp> queryRuralTourist(Long userId) {
        TouristAttractions touristAttractions = new TouristAttractions();
        touristAttractions.setSupplierId(userId);
        touristAttractions.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<TouristAttractions> touristAttractionsList = touristAttractionsMapper.queryByCondition(touristAttractions);
        if (touristAttractionsList == null || touristAttractionsList.size() == 0) {
            return null;
        }
        List<TouristAttractionsResp> touristAttractionsRespList = new LinkedList<>();
        touristAttractionsList.forEach(item -> touristAttractionsRespList.add(TouristAttractionConverter.INSTANCE.convertEntityToResp(item)));
        return touristAttractionsRespList;
    }

    @Override
    public Boolean add(TouristAttractionsReq touristAttractionsReq) {
        TouristAttractions touristAttractions = TouristAttractionConverter.INSTANCE.convertReqToEntity(touristAttractionsReq);
        touristAttractions.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        touristAttractions.setRating(0.0);
        return touristAttractionsMapper.insert(touristAttractions) > 0;
    }

    @Override
    public Boolean down(TouristAttractionsReq touristAttractionsReq) {
        // 下架农产品
        TouristAttractions touristAttractions = TouristAttractionConverter.INSTANCE.convertReqToEntity(touristAttractionsReq);
        touristAttractions.setIsDeleted(IsDeleteFlagEnum.DELETED.getCode());
        return touristAttractionsMapper.update(touristAttractions) > 0;
    }

    @Override
    public Boolean updateInfo(TouristAttractionsReq touristAttractionsReq) {
        // 更新景点信息
        TouristAttractions touristAttractions = TouristAttractionConverter.INSTANCE.convertReqToEntity(touristAttractionsReq);
        return touristAttractionsMapper.update(touristAttractions) > 0;
    }

    @Override
    public List<TouristAttractionsResp> queryBanner() {
        // 先查询redis中是否存在
        if (redisUtil.exist(RedisConstant.TOURIST_BANNER)) {
            String jsonStr = redisUtil.get(RedisConstant.TOURIST_BANNER);
            List<TouristAttractionsResp> result = JSON.parseArray(jsonStr, TouristAttractionsResp.class);
            return result;
        }
        List<TouristAttractions> touristAttractionsList = touristAttractionsMapper.queryBanner();
        List<TouristAttractionsResp> touristAttractionsRespList = new LinkedList<>();
        for (TouristAttractions touristAttractions : touristAttractionsList) {
            TouristAttractionsResp touristAttractionsResp = TouristAttractionConverter.INSTANCE.convertEntityToResp(touristAttractions);
            touristAttractionsRespList.add(touristAttractionsResp);
        }
        // 存入redis中
        if (touristAttractionsRespList != null && touristAttractionsRespList.size() > 0) {
            redisUtil.setNx(RedisConstant.TOURIST_BANNER, JSON.toJSONString(touristAttractionsRespList), 2L, TimeUnit.MINUTES);
        }
        return touristAttractionsRespList;
    }

    @Override
    public List<TouristAttractionsResp> queryHome() {
        // 查询首页热点数据
        if (redisUtil.exist(RedisConstant.TOURIST_ATTRACTIONS_HOME)) {
            String jsonStr = redisUtil.get(RedisConstant.TOURIST_ATTRACTIONS_HOME);
            List<TouristAttractionsResp> result = JSON.parseArray(jsonStr, TouristAttractionsResp.class);
            return result;
        }
        List<TouristAttractionsResp> result = new LinkedList<>();
        List<TouristAttractions> touristAttractionsList = touristAttractionsMapper.queryHome();
        touristAttractionsList.forEach(item -> {
            TouristAttractionsResp touristAttractionsResp = TouristAttractionConverter.INSTANCE.convertEntityToResp(item);
            result.add(touristAttractionsResp);
        });
        // 存入redis当中
        if (result != null && result.size() > 0) {
            redisUtil.setNx(RedisConstant.TOURIST_ATTRACTIONS_HOME, JSON.toJSONString(result), 2L, TimeUnit.MINUTES);
        }
        return result;
    }
}
